<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 引入 Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="APP">
    <div id="ddd">

    </div>

    <div id="d2">
        <select v-model="to" size="10">
            <option value="0">所有人</option>
            <option v-for="clientId in list" :key="clientId">
                {{ clientId }}
            </option>
        </select>
    </div>
    <input v-model="sendMsg"/>
    <button type="button" @click="send">发送</button>
</div>

<script>
    new Vue({
        el: '#APP',
        data: {
            recMsg: '',
            sendMsg: '',
            webSocket: null,
            list: []
        },
        mounted() {
            var clientId = Math.random().toString(16).substring(2);
            //客户端用 ws 发请求
            this.webSocket = new WebSocket("ws://localhost:8080/ws/" + clientId);
            this.webSocket.onerror = () => {
                this.appendMsg("error")
            }
            this.webSocket.onopen = () => {
                this.appendMsg("连接成功")
            }
            this.webSocket.onmessage = (event) => {
                let msg = event.data;
                if (msg.substring(0, 5) == "list-") {
                    this.updateList(msg)
                } else {
                    this.appendMsg(event.data)
                }
            }
            this.webSocket.onbeforeunload = () => {
                this.webSocket.close()
            }
        },
        methods: {
            appendMsg(recMsg) {
                let ddd = document.getElementById("ddd");
                ddd.innerHTML += recMsg + "<br/>"
            },
            send() {
                if (this.to == 0) {
                    this.webSocket.send(this.sendMsg)
                } else {
                    this.webSocket.send(this.to + "::" + this.sendMsg)
                    console.log(this.to, this.sendMsg);
                }

            },
            updateList(list) {
                list = list.substring(5);
                list = JSON.parse(list);
                this.list = list;
                // let d2 = document.getElementById("ddd");
                // d2.innerHTML = list + "<br/>"
            },
            to() {

            }
        }
    });
</script>
</body>
</html>
